import { Transfer } from 'antd';
import React, { useEffect, useState } from 'react';
import { queryAdminRoleList, queryUserAdminRolesList } from '@/pages/System/Auth/AuthRole/service';
import type {
  AdminRoleTransferItem,
  AuthRole,
  AuthRoleTableListItem,
} from '@/pages/System/Auth/AuthRole/data';

export interface AuthRoleConfigurationProps<T> {
  id: string;
  defaultValue?: AuthRole[];
  visible?: boolean;
  onChange?: (targetTransferItems: T[]) => void;
  onCancel?: (e: React.MouseEvent<HTMLElement>) => void;
  onClose?: () => void;
}

const AuthRoleConfiguration: React.FC<AuthRoleConfigurationProps<AuthRole>> = (
  params: AuthRoleConfigurationProps<AuthRole>,
) => {
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [adminRoles, setAdminRoles] = useState<AdminRoleTransferItem[]>([]);

  function adminRoleTransferItemTransfer(item: AuthRoleTableListItem): AdminRoleTransferItem {
    const transferItem: AdminRoleTransferItem = {
      key: item.id,
      title: item.name,
      description: item.name,
      disabled: false,
      ...item,
    };
    return transferItem;
  }

  function adminRoleItemTransfer(item: AdminRoleTransferItem): AuthRole {
    return {
      id: item.id,
      name: item.name,
    };
  }

  // 加载全部可选角色
  useEffect(() => {
    if (!params.id) {
      return;
    }
    queryAdminRoleList({}).then((res) => {
      const data = res.data?.flatMap((item) => adminRoleTransferItemTransfer(item)) || [];
      setAdminRoles(data);
    });
  }, ['id']);
  // 加载已选择角色
  useEffect(() => {
    if (params.defaultValue) {
      const data = params.defaultValue.flatMap((item) => adminRoleTransferItemTransfer(item));
      const fetchTargetKeys = data?.map((item) => item.key || '');
      setTargetKeys(fetchTargetKeys);
    } else {
      if (!params.id) {
        return;
      }
      queryUserAdminRolesList({ userId: params.id }).then((res) => {
        const data = res.data?.flatMap((item) => adminRoleTransferItemTransfer(item)) || [];
        const fetchTargetKeys = data?.map((item) => item.key || '');
        setTargetKeys(fetchTargetKeys);
      });
    }
  }, ['id']);

  // eslint-disable-next-line no-shadow
  const handleChange = (targets: string[], direction: string, moveKeys: string[]) => {
    if (direction === 'right') {
      setTargetKeys([...targets, ...moveKeys]);
    }

    if (direction === 'left') {
      const keys = targets.filter((o) => !moveKeys.includes(o));
      setTargetKeys(keys);
    }

    if (params.onChange) {
      const targetAdminRoles = adminRoles.filter((o) => targets.includes(o.key || ''));
      const adminRoleItems = targetAdminRoles.map((o) => adminRoleItemTransfer(o));
      params.onChange(adminRoleItems);
    }
  };

  return (
    <Transfer
      showSearch
      // style={{width: '600px', height: '500px'}}
      dataSource={adminRoles}
      listStyle={{ width: '220px', height: '450px' }}
      titles={['可分配角色', '已分配角色']}
      targetKeys={targetKeys}
      onChange={handleChange}
      selectedKeys={selectedKeys}
      onSelectChange={(sourceSelectedKeys, targetSelectedKeys) => {
        setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
      }}
      render={(item) => (item.title ? item.title : '')}
    />
  );
};
export default AuthRoleConfiguration;
